import {Component, OnInit, ViewChild} from '@angular/core';
import {FormBuilder, FormGroup} from '@angular/forms';
import {NzMessageService} from 'ng-zorro-antd/message';
import {ParkingAreaService} from '../../service/parking-area.service';
import {ParkingAreaQueryForm} from '../../types/req/ParkingAreaQueryForm';
import {SharedModule} from '../shared.module';
import {ParkingArea} from '../../types/resp/ParkingArea';
import {Page} from '../../types/page';
import {ParkingAreaAddComponent} from './parking-area-add.component';
import {ParkingAreaViewComponent} from './parking-area-view.component';
import {NzModalService} from 'ng-zorro-antd/modal';
import {BuildingSelectorComponent} from '../building/building-selector.component';
import {RoomSelectorComponent} from '../room/room-selector.component';
import { exportToExcel } from '../../utils/exportUtil'
import {getPropertyParkingAreaStatusText} from "../../utils/dictTranslator";

@Component({
  selector: 'parking-area-list',
  imports: [
    BuildingSelectorComponent,
    RoomSelectorComponent,
    ParkingAreaAddComponent,
    ParkingAreaViewComponent,
    SharedModule
  ],
  templateUrl: './parking-area-list.component.html',
  standalone: true
})
export class ParkingAreaListComponent implements OnInit {
  searchForm!: FormGroup;
  searchLoading: boolean = false
  listOfData: ParkingArea[] = [];
  total: number = 0

  @ViewChild(BuildingSelectorComponent, { static: false }) buildingSelectorComponent!: BuildingSelectorComponent;
  @ViewChild(RoomSelectorComponent, { static: false }) roomSelectorComponent!: RoomSelectorComponent;
  @ViewChild(ParkingAreaAddComponent, { static: false }) parkingAreaAddComponent!: ParkingAreaAddComponent;
  @ViewChild(ParkingAreaViewComponent, { static: false }) parkingAreaViewComponent!: ParkingAreaViewComponent;

  constructor(
    private fb: FormBuilder,
    private message: NzMessageService,
    private parkingAreaService: ParkingAreaService,
    private modal: NzModalService
  ) {}

  ngOnInit(): void {
    this.searchForm = this.fb.group({
      areaNumber: [''],
      buildingId: [0],
      buildingName: [''],
      floorNumber: [''],
      residentRoomId: [0],
      residentRoomNumber: [''],
      licensePlate: [''],
      status: [undefined],
    })
    this.onSearch()
  }

  onReset() {
    this.searchForm.reset()
  }

  onSearch() {
    try {
      this.searchLoading = true
      this.parkingAreaService.find(new ParkingAreaQueryForm(this.searchForm.value)).subscribe({
        next: (resp) => {
          if (!resp || resp.code !== 1) {
            this.message.error(resp && resp.msg ? resp.msg : '操作异常')
            return
          }
          const page: Page<ParkingArea> | undefined = resp.data
          if (page && page.list.length > 0) {
            this.listOfData = page.list
            this.total = page.total
          }
        },
        complete: () => {
          this.searchLoading = false
        }
      })
    } catch (e) {
      console.log('获取数据异常', e)
    }
  }

  onAdd() {
    this.parkingAreaAddComponent.display(0)
  }

  onExport() {
    try {
      const headers = ['车位号','楼栋名称','所在楼层','单元房号','车牌','状态']
      this.searchLoading = true
      this.parkingAreaService.find(new ParkingAreaQueryForm(this.searchForm.value)).subscribe({
        next: (resp) => {
          if (!resp || resp.code !== 1 || !resp.data || resp.data.list.length < 1) {
            this.message.error('无数据导出')
            return
          }
          const exportData = []
          for (const d of resp.data.list) {
            exportData.push([d.areaNumber,d.buildingName,d.floorNumber,d.residentRoomNumber,d.licensePlate,getPropertyParkingAreaStatusText(d.status)])
          }
          exportToExcel(headers, exportData)
        },
        complete: () => {
          this.searchLoading = false
        }
      })
    } catch (e) {
      console.log('获取数据异常', e)
    }
  }

  editRow(id: number) {
    this.parkingAreaAddComponent.display(id)
  }

  delRow(id: number) {
    this.modal.confirm({
      nzTitle: '<i>删除提示</i>',
      nzContent: '<b>确定要删除吗?</b>',
      nzOnOk: () => {
        this.parkingAreaService.del(id).subscribe({
          next: (resp) => {
            if (resp && resp.code === 1) {
              this.message.success('删除成功!')
              this.onSearch()
            } else {
              this.message.error('操作失败:' + (resp.msg ? resp.msg : '原因未知'))
            }
          },
          complete: () => {
            this.searchLoading = false
          }
        })
      }
    });
  }

  detailRow(record: ParkingArea) {
    this.parkingAreaViewComponent.display(record)
  }

  findBuilding() {
    this.buildingSelectorComponent.display()
  }

  handleBuildingSelectedEvent(selectedBuilding: { buildingId?: number; buildingName?: string; }) {
    if (selectedBuilding && 'buildingId' in selectedBuilding) {
      this.searchForm.patchValue(selectedBuilding);
    }
  }

  findRoom() {
    this.roomSelectorComponent.display()
  }

  handleRoomSelectedEvent(selectedRoom: { residentRoomId?: number; residentRoomNumber?: string; }) {
    if (selectedRoom && 'residentRoomId' in selectedRoom) {
      this.searchForm.patchValue(selectedRoom);
    }
  }

  onAdded(addedFlag: boolean) {
    if (addedFlag) {
      this.onSearch()
    }
  }
}
